#include"../include/MyChild.h"
#include<qfileinfo.h>
#include<QCloseEvent>
#include<qfiledialog.h>
#include<qtextdocumentwriter.h>
#include<qmessagebox.h>
#include<QTextCharFormat>
#include<QTextListFormat>
#include<QTextList>

MyChild::MyChild(QWidget* parent):QTextEdit(parent)
{
	this->setAttribute(Qt::WA_DeleteOnClose);	//设置在子窗口关闭时销毁这个类的对象
	isUntitled = true;
}

MyChild::~MyChild()
{
}

void MyChild::newFile()
{
	//设置窗口编号，因为编号会一直被保存，所以需要静态变量
	static int sequenceNumber = 1;
	//新建的文档默认未命名
	isUntitled = true;
	//将当前文档命名为“文档+编号”的形式，编号+1
	curFile = tr("文档 %1").arg(sequenceNumber++);
	//设置窗口标题，使用[*]可以在文档被更改后在文件名称后显示“*”号
	this->setWindowTitle(curFile + "[*]" + tr(" - mySelf Word"));
	//文档更改时发送--信号，执行documentWasModified()槽函数
	//connect(document(), SIGNAL(), this, SLOT(documentWasModified()));
	/*connect(this->document(),&QTextDocument::contentsChanged,
			this,&MyChild::documentWasModified);*/
}

const QString MyChild::userFriendlyCurrentFile()
{
	return this->strippedName(curFile);
}

const QString MyChild::currentFile()
{
	return curFile;
}

bool MyChild::loadFile(const QString& fileName)
{
	if (!fileName.isEmpty()) {
		if (!QFile::exists(fileName))
			return false;
		QFile file(fileName);
		if (!file.open(QFile::ReadOnly))
			return false;
		//QByteArray data = file.readAll();
		QString str = QString::fromUtf8(file.readAll());
		if (Qt::mightBeRichText(str))
			this->setHtml(str);
		else {
			str = QString::fromLocal8Bit(file.readAll());
			this->setPlainText(str);
		}
		//设置当前文件
		this->setCurrentFile(fileName);
		connect(this->document(), &QTextDocument::contentsChanged, this, &MyChild::documentWasModified);
	}
	else
		return false;
	return true;
}

bool MyChild::save()
{
	if (isUntitled)
		return this->saveAs();
	else
		return this->saveFile(curFile);
}

bool MyChild::saveAs()
{
	QString fileName = QFileDialog::getSaveFileName(this, tr("另存为"), curFile,
		tr("HTML 文档 (*.htm *.html);;所有文件(*.*)"));
	if (fileName.isEmpty())
		return false;
	return this->saveFile(fileName);
}

bool MyChild::saveFile(QString& fileName)
{
	if (!(fileName.endsWith(".htm", Qt::CaseInsensitive) || fileName.endsWith(".html", Qt::CaseInsensitive)))
		fileName += ".html";
	QTextDocumentWriter writer(fileName);
	bool success = writer.write(this->document());
	if (success)	this->setCurrentFile(fileName);
	return success;
}

void MyChild::mergeFormatOnSelection(const QTextCharFormat& format)
{
	QTextCursor cursor = this->textCursor();
	if (!cursor.hasSelection())
		cursor.select(QTextCursor::WordUnderCursor);
	cursor.mergeCharFormat(format);
	this->mergeCurrentCharFormat(format);
}

void MyChild::setStyle(int style)
{
	QTextCursor cursor = this->textCursor();
	if (style != 0) {
		//QTextListFormat主要用于描述文本标号，编号的格式
		QTextListFormat::Style styleName = QTextListFormat::ListDisc;
		switch (style)
		{
		case 1:	styleName = QTextListFormat::ListDisc; break;		//实心圆标号
		case 2: styleName = QTextListFormat::ListCircle; break;		//空心圆标号
		case 3: styleName = QTextListFormat::ListSquare; break;		//方形标号
		case 4: styleName = QTextListFormat::ListDecimal; break;	//十进制编号
		case 5: styleName = QTextListFormat::ListLowerAlpha; break;	//小写字母编号
		case 6: styleName = QTextListFormat::ListUpperAlpha; break;	//大写字母编号
		case 7: styleName = QTextListFormat::ListLowerRoman; break;	//小写罗马编号
		case 8: styleName = QTextListFormat::ListUpperRoman; break;	//大写罗马编号
		default:
			break;
		}
		//为支持撤销操作
		cursor.beginEditBlock();
		QTextBlockFormat blockFmt = cursor.blockFormat();
		QTextListFormat listFmt;
		if (cursor.currentList()) 
			listFmt = cursor.currentList()->format();
		else {
			listFmt.setIndent(blockFmt.indent() + 1);
			blockFmt.setIndent(0);
			cursor.setBlockFormat(blockFmt);
		}
		listFmt.setStyle(styleName);
		cursor.createList(listFmt);
		cursor.endEditBlock();
	}
	else {
		QTextBlockFormat bfmt;
		bfmt.setObjectIndex(-1);
		cursor.mergeBlockFormat(bfmt);
	}
}

void MyChild::setAlign(int align)
{
	if (align == 1)
		this->setAlignment(Qt::AlignLeft | Qt::AlignAbsolute);
	else if (align == 2)
		this->setAlignment(Qt::AlignHCenter);
	else if (align == 3)
		this->setAlignment(Qt::AlignRight | Qt::AlignAbsolute);
	else if (align == 4)
		this->setAlignment(Qt::AlignJustify);
}

void MyChild::closeEvent(QCloseEvent* event)
{
	//先无脑关闭
	event->accept();
}

void MyChild::setCurrentFile(const QString& fileName)
{
	curFile = QFileInfo(fileName).canonicalFilePath();
	//文件已被保存过
	isUntitled = false;
	//文档未被更改过
	this->document()->setModified(false);
	//窗口不显示被更改标志
	this->setWindowModified(false);
	//设置窗口标题
	this->setWindowTitle(this->userFriendlyCurrentFile() + "[*]");
}

bool MyChild::maybeSave()
{
	if (!this->document()->isModified())
		return true;
	QMessageBox::StandardButton ret;
	ret = QMessageBox::warning(this, tr("mySelf Qt Word"),
		tr("文档 '%1'已被修改，是否保存？").arg(this->userFriendlyCurrentFile()),
		QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel);
	if (ret == QMessageBox::Save)
		return this->save();
	else if (ret == QMessageBox::Cancel)
		return false;
	return true;
}

const QString MyChild::strippedName(const QString& fullFileName)
{
	return QFileInfo(fullFileName).fileName();
}

void MyChild::documentWasModified() {
	//根据文档的isModified()函数的返回值，判断编辑器内容是否被更改
	this->setWindowModified(this->document()->isModified());
}
